<?php

require_once 'inc/header.php';

$stmt = $db->prepare('SELECT content FROM posts WHERE user_fbid=?');
$stmt->execute(array($_SESSION['me']['fbid']));
$resultset = $stmt->fetchAll();
$postcount = count($resultset);
if($resultset){
//TODO:
//Start Shouting
$totalCharCount = 0;
$upperCaseCount = 0;
$upperCasePattern = "/[A-Z]/";
foreach($resultset as $r)
{
   $chars = str_split($r['content']);
   
   foreach($chars as $c)
   {
       $upperCaseCount+=preg_match_all($upperCasePattern,$c,$matches);
       $totalCharCount++;
   }
}
$shoutinggraph = number_format($upperCaseCount/$totalCharCount*100,2);
$shoutingPercentage = $shoutinggraph.'% of all posts';
//End Shouting
//
//Start Happy 
//
//
//Start Cursing
$cursewords = array("fuck","suck","hate","stupid","fking");

$cursingcount = 0;
foreach($resultset as $cp)
{
   $filteredpost = str_replace($cursewords, "[CURSEWORDS]", $cp['content']);
   if(strpos($filteredpost, "[CURSEWORDS]")!==false)
   {
     $cursingcount++;   
   }
}
$cursinggraph =number_format($cursingcount/$postcount*100,2);
$cursingcountpercent = $cursinggraph.'% of all posts';
//

//End Cursing
//
//Start Talkative post per week
$stmt = $db->prepare('SELECT UNIX_TIMESTAMP(MIN(dt)) AS t FROM posts WHERE user_fbid=?');
$stmt->execute(array($_SESSION['me']['fbid']));
$resulttime=$stmt->fetch();
$weekscount = (time()- $resulttime['t'])/86400/7;

$talkativegraph = number_format($postcount/$weekscount,2);
$talkativePostPerDay = $talkativegraph.' posts per week';

    
 //End Talkative

//Start Hesitant
//define pattern as '/\.{1,}/' for testing purpose
//else, ellipses(...)({3,})
//if hit then make it to one post
$hesitantpattern = '/\.{3,}/';
$totalhesitantcount = 0;
foreach($resultset as $h)
{
    //$wordsp = explode(" ",$h['content']);
    //$totalhesitantcount+=preg_match_all($hesitantpattern,$wc,$matches);
    if(strpos($h['content'], "...")!==false)
    {
        $totalhesitantcount++;
    }   
    
}

$hesitantgraph = number_format($totalhesitantcount/$postcount*100,2);
$hesitantpercent = $hesitantgraph.'% of all posts';

//End Hesitant
//Grammar Nazi
$grammarnazipattern = '/[:;()\'\"\.\-\!\^\$\+\*\|]/';
$punctuationcount =0;
foreach($resultset as $g)
{
        //number of punctuation characters
        $punctuationcount += preg_match_all($grammarnazipattern,$g['content'],$matches);
}
$grammarnazigraph = number_format($punctuationcount/$totalCharCount*100,2);
$grammarnazipercentage = $grammarnazigraph.'% of all posts';

$friends = $db->q('
	SELECT fbid, name
	FROM users
	WHERE fbid
	IN (
		SELECT friend_fbid fbid
		FROM friends
		WHERE user_fbid = ?
	)
	ORDER BY name
', $_SESSION['me']['fbid']);
?>

			<div class="section">
				<div id="comparePostsContainer">
					Compare with 
					<select id="comparePostsWith">
						<option value="0">None</option>
						<?php foreach ($friends as $f) printf('<option value="%s">%s</option>', htmlentities($f['fbid']), htmlentities($f['name'])); ?>
					</select>
				</div>
				<!--<table id="statistics">
					<tr><td>Shouting</td><td><?php echo($shoutingPercentage);?></td></tr>
					<tr><td>Cursing</td><td><?php echo($cursingcountpercent);?></td></tr>
					<tr><td>Talkative</td><td><?php echo($talkativePostPerDay);?></td></tr>
					<tr><td>Hesitant</td><td><?php echo($hesitantpercent);?></td></tr>
					<tr><td>Grammar Nazi</td><td><?php echo($grammarnazipercentage);?></td></tr>
				</table>-->
				<div id="postRadar"></div>
			</div>		

<script type="text/javascript">

var chartData = [
	{ 'name': 'Shouting', 'data1': <?php echo($shoutinggraph);?>, data2: 0 },
	{ 'name': 'Cursing',   'data1': <?php echo($cursinggraph);?>, data2: 0 },
	{ 'name': 'Talkative', 'data1': <?php echo($talkativegraph);?>, data2: 0 },
	{ 'name': 'Hesitant',  'data1': <?php echo($hesitantgraph);?>, data2: 0 },
	{ 'name': 'Grammar Nazi', 'data1': <?php echo($grammarnazigraph);?>, data2: 0}
];

var store = Ext.create('Ext.data.JsonStore', {
    fields: ['name', 'data1', 'data2'],
    data: chartData
});

var chart;

Ext.onReady(function() {
    Ext.QuickTips.init();
    chart = new Ext.chart.Chart({
        renderTo: Ext.get('postRadar'),
        width: 400,
        height: 300,
        animate: true,
        theme:'Category2',
        store: store,
        axes: [{
            type: 'Radial',
            position: 'radial',
            label: {
                display: true
            }
        }],
    
 series: [{
            
            type: 'radar',
            xField: 'name',
            yField: 'data1',
            showInLegend: true,
            showMarkers: true,
            highlight : true,
			shadow: false,
			tips: {
				cls: 'chartTooltip',
				width: 140,
				height: 28,
				renderer: function(storeItem, item) {
                                    var desc;
                                    switch(storeItem.get('name')){
                                        case "Cursing":
                                        desc = "Vulgars";
                                        break;
                                        case "Hesitant":
                                            desc="Triple dots";
                                            break;
                                        case "Shouting":
                                            desc="Capital Letters";
                                            break;
                                        case "Grammar Nazi":
                                            desc="Punctuation";
                                            break;
                                        case "Talkative":
                                            desc="Talk alot"
                                            break;
                                    }
                                       
					this.setTitle(storeItem.get('name') + ' = ' + storeItem.get('data1')+"<br>"+desc);
				}
			},
                        listeners:
                            {
                                'itemmousedown':function(o)
                                {
                                    $.get('post_samples.php?signed_request=<?php if (!empty($_POST['signed_request'])) echo $_POST['signed_request']; ?>&category=' + o.storeItem.data.name, function(data) {
                                        for (var i = 0; i < data.length; i++) {
                                            alert(data[i]);
                                        }
                                    });
                                }
                            
                            },
            markerConfig: {
                radius: 5,
                size: 5
            },
            style: {
                'stroke-width': 2,
                fill: 'none'
            }
            /*tips: {
              trackMouse: true,
              width: 140,
              height: 28
              renderer: function(storeItem, item) {
                this.setTitle(storeItem.get('name') + ': ' + storeItem.get('data1') + ' views');
              }
            }*/
        }]
    });
});

var secondseriesadded = false;
$('#comparePostsWith').change(function() {
		var fbid = +$(this).val();
               
		if (fbid) {
			$('#notice').text('Pulling wall post data...').slideDown('fast');
			$.get('post_data.php?signed_request=<?php if (!empty($_POST['signed_request'])) echo $_POST['signed_request']; ?>&fbid=' + fbid, function(data) {
                                if(!secondseriesadded){
                                   
                                secondseriesadded = true;
                                
                                chart.series.add({
					type: 'radar',
					xField: 'name',
					yField: 'data2',
					showInLegend: true,
					showMarkers: true,
                                        highlight : true,
                                        shadow : false,
                                        tips: {
				cls: 'chartTooltip',
				width: 140,
				height: 28,
				renderer: function(storeItem, item) {
                                    var desc;
                                    switch(storeItem.get('name')){
                                        case "Cursing":
                                        desc = "Vulgars";
                                        break;
                                        case "Hesitant":
                                            desc="Triple dots";
                                            break;
                                        case "Shouting":
                                            desc="Capital Letters";
                                            break;
                                        case "Grammar Nazi":
                                            desc="Punctuation";
                                            break;
                                        case "Talkative":
                                            desc="Talk alot"
                                            break;
                                    }
                                       
					this.setTitle(storeItem.get('name') + ' = ' + storeItem.get('data2')+"<br>"+desc);
				}
			},
					markerConfig: {
						radius: 5,
						size: 5
					},
					style: {
						'stroke-width': 2,
						fill: 'none'
					}
				});
                                
                                }
				for (var i = 0; i < chartData.length; i++) chartData[i].data.data2 = data[chartData[i].data.name];
				chart.store.loadData(chartData);
                                chart.series.pop();
				chart.redraw();
				$('#notice').slideUp('fast', function() {
					$(this).empty();
				});
			});
		} 
                
	});

</script>
<?php
}
else
    {
    echo("No data available");
    }

                    
                    require_once 'inc/footer.php';
                    ?>
